package com.Cychat.chat.controller;

import com.Cychat.chat.util.WebSocketUtil;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api/chat")
public class NotificationController {

    /**
     * 接收来自其他服务的通知消息并推送给指定用户
     * 
     * @param message 消息内容
     * @return 响应结果
     */
    @PostMapping("/sendNotification")
    public ResponseEntity<String> sendNotification(@RequestBody Map<String, Object> message) {
        try {
            System.out.println("========== 开始发送通知消息 ==========");

            // 获取消息参数
            Object toIdObj = message.get("toId");
            Object fromIdObj = message.get("fromId");
            Object msgObj = message.get("msg");
            Object nameObj = message.get("name");
            Object headImgObj = message.get("headImg");
            Object messageTypeObj = message.get("messageType");
            Object actionObj = message.get("action"); // 获取action字段

            if (toIdObj == null || fromIdObj == null || msgObj == null) {
                System.err.println("消息缺少必要参数");
                return ResponseEntity.badRequest().body("消息缺少必要参数");
            }

            Long receiverId = Long.valueOf(toIdObj.toString());
            Long senderId = Long.valueOf(fromIdObj.toString());
            String content = msgObj.toString();
            String senderName = nameObj != null ? nameObj.toString() : "系统通知";
            String senderAvatar = headImgObj != null ? headImgObj.toString() : null;
            String messageType = messageTypeObj != null ? messageTypeObj.toString() : "notification";
            String action = actionObj != null ? actionObj.toString() : null; // 获取action值

            System.out.println("接收者ID: " + receiverId);
            System.out.println("发送者ID: " + senderId);
            System.out.println("消息内容: " + content);
            System.out.println("发送者昵称: " + senderName);
            System.out.println("消息类型: " + messageType);
            System.out.println("操作类型: " + action); // 打印action字段
            System.out.println("当前在线用户列表: " + WebSocketUtil.MESSAGEMAP.keySet());

            // 发送通知消息（带action字段）
            WebSocketUtil.sendNotificationMessage(receiverId, senderId, content, senderName, senderAvatar, messageType,
                    action);

            System.out.println("========== 通知消息发送流程结束 ==========");
            return ResponseEntity.ok("消息发送成功");
        } catch (Exception e) {
            System.err.println("发送通知消息时发生异常: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.status(500).body("消息发送失败: " + e.getMessage());
        }
    }
}